<template>
  <div class="role-container-padding">
    <vxe-grid
      ref="xGrid"
      border
      stripe
      keep-source
      auto-resize
      sync-resize
      :height="height"
      :loading="listLoading"
      size="small"
      :column-config="{ resizable: true }"
      :export-config="{}"
      :columns="tableColumn"
      align="center"
      :row-config="{ keyField: 'id', isCurrent: true, isHover: true }"
      :seq-config="{ seqMethod: seqMethod }"
    >
      <template #form>
        <vxe-form
          ref="queryform"
          title-align="right"
          title-width="120"
          prevent-submit
        >
          <vxe-form-item title="岗位名称" span="8">
            <template #default>
              <el-input
                v-model="queryForm.name"
                placeholder="角色名称"
                style="width: 150px"
                clearable
              />
            </template>
          </vxe-form-item>
          <vxe-form-item title="岗位编码" span="8">
            <template #default>
              <el-input
                v-model="queryForm.code"
                placeholder="岗位编码"
                style="width: 150px"
                clearable
              />
            </template>
          </vxe-form-item>
          <vxe-form-item title="状态" span="8">
            <template #default>
              <el-select
                v-model="queryForm.status"
                placeholder="请选择状态"
                size="large"
                style="width: 240px"
                clearable
              >
                <el-option
                  v-for="item in statusOpt"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </template>
          </vxe-form-item>
          <vxe-form-item span="24" align="center">
            <el-button
              v-permissions="{ permission: ['system:post:query'] }"
              :icon="Search"
              plain
              @click="queryData"
            >
              查询
            </el-button>
            <el-button
              v-permissions="{ permission: ['system:post:create'] }"
              :icon="Plus"
              type="primary"
              plain
              @click="handleEdit($event)"
            >
              添加
            </el-button>
            <el-button
              v-permissions="{ permission: ['system:post:export'] }"
              type="success"
              plain
              :loading="exportLoading"
              @click="handleExport"
            >
              <i class="iconfont-fw ri-download-2-line" />
              导出
            </el-button>
          </vxe-form-item>
        </vxe-form>
      </template>
      <template #bottom>
        <el-pagination
          background
          :current-page="queryForm.pageNo"
          :layout="layout"
          :page-size="queryForm.pageSize"
          :total="total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </template>
      <template #status="{ row }">
        <div>
          <el-tag :type="row.status == 0 ? 'success' : 'danger'" hit>
            {{ row.status == 0 ? '&emsp;开启&emsp;' : '&emsp;关闭&emsp;' }}
          </el-tag>
        </div>
      </template>
      <template #operate="{ row }">
        <div>
          <el-button
            v-permissions="{ permission: ['system:post:update'] }"
            type="primary"
            size="small"
            plain
            :icon="Edit"
            @click="handleEdit(row)"
          >
            编辑
          </el-button>
          <el-button
            v-permissions="{ permission: ['system:post:delete'] }"
            size="small"
            type="danger"
            plain
            @click="handleDelete(row)"
          >
            <el-icon class="el-icon--right">
              <Delete />
            </el-icon>
            删除
          </el-button>
        </div>
      </template>
    </vxe-grid>

    <postEdit ref="editRef" @fetch-data="fetchData" />
  </div>
</template>

<script>
  import { deletePost, exportPost, getPostPage } from '@/api/system/post'
  import download from '@/utils/download'
  import { Delete, Edit, Plus, Search } from '@element-plus/icons-vue'

  export default defineComponent({
    name: 'Post',
    components: {
      postEdit: defineAsyncComponent(() => import('./components/postEdit')),
    },
    setup() {
      const $baseConfirm = inject('$baseConfirm')
      const $baseMessage = inject('$baseMessage')
      const $baseTableHeight = inject('$baseTableHeight')
      const state = reactive({
        height: $baseTableHeight(0),
        xGrid: 'xGrid',
        editRef: null,
        userRoleRef: null,
        exportLoading: false,
        tableColumn: [
          { type: 'checkbox', width: 50, fixed: 'left' },
          { type: 'seq', title: '序号', width: 50, fixed: 'left' },
          {
            title: '岗位名称',
            field: 'name',
            minWidth: 160,
          },
          {
            title: '岗位编码',
            field: 'code',
            width: 160,
          },
          {
            title: '备注',
            field: 'remarks',
            minWidth: 120,
          },
          {
            title: '状态',
            width: 90,
            slots: { default: 'status' },
          },
          {
            title: '排序',
            field: 'sort',
            width: 80,
          },
          {
            title: '操作',
            minWidth: 200,
            fixed: 'right',
            slots: { default: 'operate' },
          },
        ],
        list: [],
        listLoading: false,
        layout: 'total, sizes, prev, pager, next, jumper',
        total: 0,
        selectRows: '',
        queryForm: {
          pageNo: 1,
          pageSize: 30,
          remark: '',
        },
        statusOpt: [
          { label: '开启', value: 0 },
          { label: '状态', value: 1 },
        ],
      })

      const setSelectRows = (val) => {
        state.selectRows = val
      }

      const handleEdit = (row) => {
        if (row.id) {
          state['editRef'].showEdit(row)
        } else {
          state['editRef'].showEdit()
        }
      }

      const handleDelete = (row) => {
        if (row) {
          $baseConfirm('你确定要删除当前项吗', null, async () => {
            const { msg } = await deletePost(row.id).catch((err) => {
              state.listLoading = false
            })
            $baseMessage(msg, 'success', 'vab-hey-message-success')
            await fetchData()
          })
        } else {
          $baseMessage('未选中任何行', 'error', 'vab-hey-message-error')
        }
      }

      const handleSizeChange = (val) => {
        state.queryForm.pageSize = val
        fetchData()
      }

      const handleCurrentChange = (val) => {
        state.queryForm.pageNo = val
        fetchData()
      }

      const queryData = () => {
        state.queryForm.pageNo = 1
        fetchData()
      }

      const fetchData = async (val) => {
        state.listLoading = true
        getPostPage(state.queryForm)
          .then((res) => {
            if (res.code == 0 || res.code == 200) {
              state['xGrid'].reloadData(res.data.list)
              state.total = res.data.total
              state.listLoading = false
            } else {
              state.listLoading = false
            }
          })
          .catch((err) => {
            state.listLoading = false
          })
      }

      const handleExport = async () => {
        state.exportLoading = true
        const data = await exportPost(state.queryForm)
        download.excel(data, '岗位列表.xls')
        state.exportLoading = false
      }

      const seqMethod = ({ row, rowIndex, column, columnIndex }) => {
        return (
          (state.queryForm.pageNo - 1) * state.queryForm.pageSize + rowIndex + 1
        )
      }

      onMounted(() => {
        fetchData()
      })

      onBeforeMount(() => {
        window.addEventListener('resize', handleHeight)
      })

      onBeforeUnmount(() => {
        window.removeEventListener('resize', handleHeight)
      })

      const handleHeight = () => {
        state.height = $baseTableHeight(0)
      }

      return {
        ...toRefs(state),
        setSelectRows,
        handleEdit,
        handleDelete,
        handleSizeChange,
        handleCurrentChange,
        queryData,
        fetchData,
        Edit,
        Delete,
        Plus,
        Search,
        seqMethod,
        handleExport,
      }
    },
  })
</script>
